package com.adam.management.filter;

import com.adam.management.pojo.User;
import com.adam.management.util.SessionParameter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String uri = request.getRequestURI();
        if(uri.contains("style")||uri.contains("login")||uri.contains("register")||uri.contains("signin")){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            Object attribute = request.getSession().getAttribute(SessionParameter.USER_INFO);
            if(attribute!=null&&attribute instanceof User){
                filterChain.doFilter(servletRequest,servletResponse);
            }else {
                response.sendRedirect("/user/login");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
